/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * http://stackoverflow.com/questions/5629122/defaulthttpclient-certificates-https-and-posting-problem
 * http://www.exampledepot.com/egs/javax.net.ssl/trustall.html
 */
package isas;

import java.io.UnsupportedEncodingException;
import javax.swing.JOptionPane;
import java.net.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 *
 * @author Kubik
 */
public class Login {
    //URL url = null;
    
    public Login(String strUrl, String login, String password) throws java.io.IOException, Exception{
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\Ahttps?:\\/\\/[\\d\\w.:\\/?&=\\+]+");
        java.util.regex.Matcher matcher = pattern.matcher(strUrl);
        if(!matcher.find()){
            throw new java.io.IOException("Vložený text nevypadá jako URL!");
        }     
        //this.url = new URL(strUrl);
        
        String data;
        
        data = URLEncoder.encode("login-isas-username", "UTF-8") + "=" + URLEncoder.encode(login, "UTF-8");
        data += "&"+URLEncoder.encode("login-isas-password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
        data += "&"+URLEncoder.encode("login-isas-send", "UTF-8") + "=" + URLEncoder.encode("isas-send", "UTF-8");
        
        // Debug
        //JOptionPane.showMessageDialog(null, data);
        // Debug end
        
        HttpsURLConnection httpCon = initializeConnection(data, new URL(strUrl), "POST");
        //boolean pause = true;
        if(httpCon!=null){
            try (java.io.DataOutputStream os = new java.io.DataOutputStream(httpCon.getOutputStream())) {
                os.writeBytes(data);
                os.flush();
                //debug
                java.io.BufferedReader BRresponse = new java.io.BufferedReader(new java.io.InputStreamReader(httpCon.getInputStream()));
                String StrResponse = "";
                String s;
                while((s = BRresponse.readLine()) != null){
                    StrResponse+= s;
                }
                boolean pause = true;
                //debug end
            }
        }
    }
    
    // method that trusts to all SSL/TLS certificates
    public static HttpsURLConnection initializeConnection(String data, URL url, String reqMethod) throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override
                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
                @Override
                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };
        
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            JOptionPane.showMessageDialog(null, "All-Trusting trust mgr error! "+e.getMessage());
        }
        
        HttpsURLConnection httpCon = (HttpsURLConnection)url.openConnection();

        // set connection parameters
        if(reqMethod != null && !reqMethod.isEmpty())
            httpCon.setRequestMethod(reqMethod);
        
        httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpCon.setRequestProperty("User-Agent", "Java");
        httpCon.setRequestProperty("Content-Length", Integer.toString(data.length()));
        httpCon.setRequestProperty("Connection", "close");
        httpCon.setReadTimeout(50000);
        httpCon.setUseCaches(false);
        httpCon.setDoInput(true);
        httpCon.setDoOutput(true);
        httpCon.connect();

        return httpCon;
    }
    
}
